<?php

use Doraemon\cache\UserCounter;
use Doraemon\model\Article;
use Doraemon\model\ArticlePhoto;
use Doraemon\model\Favorite as DbFavorite;
use Doraemon\model\Like as mLike;
use Doraemon\model\Photos;
use Doraemon\service\Favorite;
use Doraemon\service\Like;
use Doraemon\tools\Log;
use Doraemon\service\DesignerInfoLib\OperateInfoService as sOperateInfo;

class DelArticleAction extends ActionPlugin
{
    const IS_TRACING = true;

    /**
     * 迁移hhzhome队列 - 删除整屋
     */
    public function main()
    {
        Log::info('DelArticle操作接收到的订阅消息', $this->messageBody);

        if (!$this->messageBody['database']) throw new \Exception('未获取到数据库');
        if (!$this->messageBody['table']) throw new \Exception('未获取到数据表');
        if (!$this->messageBody['data']) throw new \Exception('未接收到数据');

        $sArticleId = $this->messageBody['data']['aid'];
        $iUid = $this->messageBody['data']['uid'];
        $iStatus = $this->messageBody['data']['status'];

        if (in_array($iStatus, Article::GROUP_DEL, true)) {
            //获取文章全部空间信息
            $aArticleSpaceData = ArticlePhoto::getArticleSpaceInfoByIds($sArticleId);
            if (!empty($aArticleSpaceData)) {
                //获取文章的单图id结果集
                foreach ($aArticleSpaceData as $aAtivespace) {
                    $aShowPics = json_decode($aAtivespace['show_pics'], true, 512, JSON_THROW_ON_ERROR);
                    foreach ($aShowPics as $aCurrentPhoto) {
                        $aPhotoIds[] = $aCurrentPhoto['photo_id'];
                    }
                }
                //切断文章和图片的关系
                if (!empty($aPhotoIds)) {
                    foreach ($aPhotoIds as $sPhotoId) {
                        Photos::updatePhotoById($sPhotoId, ['type' => 0, 'article_id' => '']);
                    }
                }
            }
            // 扣除当前删除文章的点赞数&收藏数
            $iLikeNum = Like::delLikeByObjId($sArticleId, mLike::LIKE_TYPE_ARTICLE);
            if ($iLikeNum) {
                UserCounter::decreaseUserCounter($iUid, UserCounter::TYPE_BELIKED, -$iLikeNum);
            }
            $iFavoriteNum = Favorite::delFavoriteByObjId($sArticleId, DbFavorite::TYPE_ARTICLE);
            if ($iFavoriteNum) {
                UserCounter::decreaseUserCounter($iUid, UserCounter::TYPE_BEFAVED, -$iFavoriteNum);
            }
            // 更新设计师信息库中的整屋优质率
            sOperateInfo::updateArticleHighRate($iUid);
        }
        $this->setSuccess();
    }
}
